package com.ellwood.IPGuard.common.core.exception;

import com.ellwood.IPGuard.common.core.constants.HttpStatus;
import com.ellwood.IPGuard.common.core.result.EllResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

/**
 * @ProjectName: IPGuard-boot
 * @PackageName: com.ellwood.IPGuard.common.core.exception
 * @ClassName: ServerExceptionHandler
 * @Description: // 异常处理器
 * @Author: Ellwood
 * @CreateDate: 2024/9/25 - 下午4:14
 * @Version: V1.0.0
 */
@Slf4j
@RestControllerAdvice
public class ServerExceptionHandler {

    @ExceptionHandler(Exception.class)
    public EllResult handleException(Exception e){
        log.error("Exception: ", e);
        return EllResult.error(ErrorCode.INTERNAL_SERVER_ERROR.getMsg());
    }

    /**
     * 自定义异常处理
     * @param se 异常参数
     * @return 返回自定义异常结果
     */
    @ExceptionHandler(ServerException.class)
    public EllResult handleException(ServerException se){
        return EllResult.error(se.getCode(),se.getMsg());
    }
        
        /**
         * 自定义 系统异常处理
         *
         * @param syse 系统异常参数
         * @return 返回系统异常结果
         */
        @ExceptionHandler(SystemException.class)
        public EllResult systemHandleException(SystemException syse) {
                return EllResult.error(syse.getCode(), syse.getMsg());
        }

    /**
     * SpringMVC参数绑定，Validator校验不正确
     * @param be 参数异常
     * @return 返回异常结果
     */
    @ExceptionHandler(BindException.class)
    public EllResult bindException(BindException be){
        FieldError fieldError = be.getFieldError();
        assert fieldError != null;
        return EllResult.error(fieldError.getDefaultMessage());
    }

    @ExceptionHandler(NoResourceFoundException.class)
    public ResponseEntity<String> handleResourceNotFoundException(NoResourceFoundException nrfe){
        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body("404 Not Found:"+nrfe.getResourcePath());
    }

    /*
    TODO 后期引入权限框架之后再使用
    @ExceptionHandler(AccessDeniedException.class)
    public EllResult handleAccessDeniedException(Exception ex) {

        return EllResult.error(ErrorCode.FORBIDDEN.getMsg());
    }*/

}
